import json
import time
import traceback

from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.core.paginator import Paginator
from django.shortcuts import render

from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.views import APIView

from goodsManage import models
from merchant import models as mc_models
from goodsManage.serializers import GoodsTypeSeriallizer, GoodsSeriallizer
from logsManage.views import set_server_logs

from tools.authToken import create_token, userAuth
from tools.encryption import getSha256, getDataAes, setDataAes
from tools.log import logger
from tools.tool import get_ip, get_json_values, get_file_type, get_time_uid, delete_file, imgType_list

from Wchime import settings


# 商品列表
class GoodList(APIView):
    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')
            merchants = mc_models.MerchantInfo.objects.filter(master_id=user_id).last()
            ip = get_ip(request)
            body = request.query_params.dict()
            goods = models.Goods.objects.filter(master_id=merchants.id).order_by('sort', 'id')

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)

            paginator = Paginator(goods, page_size)
            goods = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = GoodsSeriallizer(goods, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total': total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')
            ip = get_ip(request)
            body = request.POST.dict()
            # body = json.loads(request.body)
            body = request.POST.dict()
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)
            type_id = get_json_values("type_id", body, None)
            price = get_json_values("price", body, 0.00)
            # shelf = get_json_values("shelf", body, 0)
            img = request.FILES.get("img", None)
            filepath = None
            # icon_type = ''
            # file_name = ''
            if img:
                file_nem, file_type = get_file_type(str(img))
                if file_type not in imgType_list:
                    li.append('不支持该格式')
                    resp = {"success": 0, "data": li}
                    return Response(resp)
                file_name = get_time_uid()
                filepath = '/{}/{}/{}'.format('media', 'goods', file_name + file_type)
                openfile = settings.MEDIA_ROOT + '/goods/' + file_name + file_type
                with open(openfile, 'wb+') as temp_file:
                    for chunk in img.chunks():
                        temp_file.write(chunk)

            if models.Goods.objects.create(
                    name=name,
                    sort=sort,
                    describe=describe,
                    master_id=user_id,
                    type_id=type_id,
                    price=price,
                    shelf=1,
                    img=filepath
            ):

                resp = {"code": 1, "data": li, "msg": '新建成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '新建失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)


    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            # body = json.loads(request.body)
            body = request.POST.dict()
            id = get_json_values("id", body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)

            price = get_json_values("price", body, 0.00)
            shelf = get_json_values("shelf", body, 0)

            file = request.FILES.get("img", None)
            filepath = None
            # icon_type = ''
            # file_name = ''
            item = models.Goods.objects.filter(id=id)
            if file:
                file_nem, file_type = get_file_type(str(file))
                if file_type not in imgType_list:
                    li.append('不支持该格式')
                    resp = {"success": 0, "data": li}
                    return Response(resp)
                file_name = get_time_uid()
                filepath = '/{}/{}/{}'.format('media', 'goods', file_name + file_type)
                openfile = settings.MEDIA_ROOT + '/goods/' + file_name + file_type
                with open(openfile, 'wb+') as temp_file:
                    for chunk in file.chunks():
                        temp_file.write(chunk)
                item.update(
                    img=filepath
                )

            if item.update(
                    name=name,
                    sort=sort,
                    describe=describe,
                    shelf=shelf,
                    price=price
            ):
                resp = {"code": 1, "data": li, "msg": '修改成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '修改失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            id_list = get_json_values("id", body)
            # print(id_list)
            goods = models.Goods.objects.filter(id__in=id_list)
            for rm in goods:
                if rm.img:
                    delete_file(settings.BASE_DIR+rm.img)
            goods.delete()

            resp = {"code": 1, "data": li,"msg": "删除成功"}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

# 商品类型
class GoodsType(APIView):

    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            types = models.GoodsType.objects.filter().order_by('sort')
            all = get_json_values("all", body)
            if all:
                seriallizer = GoodsTypeSeriallizer(types, many=True)
                resp = {"code": 1, "data": seriallizer.data}
                return Response(resp)

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)

            paginator = Paginator(types, page_size)
            types = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = GoodsTypeSeriallizer(types, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total': total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = json.loads(request.body)

            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body)

            types = models.GoodsType.objects.create(
                name=name,
                sort=sort,
                describe=describe
            )
            if types:
                resp = {"code": 1, "data": li, 'msg': "新增成功"}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            id = get_json_values("id", body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)

            if models.GoodsType.objects.filter(id=id).update(
                name=name,
                sort=sort,
                describe=describe
            ):
                resp = {"code": 1, "data": li, "msg": '修改成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '修改失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            id_list = get_json_values("id", body)
            # print(id_list)
            goodType = models.GoodsType.objects.filter(id__in=id_list)
            goodType.delete()

            resp = {"code": 1, "data": li, "msg": "删除成功"}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)
